package com.hynet.customer.client;

import com.alibaba.fastjson.JSON;
import com.aliyun.tea.*;
import com.hynet.customer.client.models.ApiResponse;
import com.hynet.customer.client.models.Config;


public class Client {


    public String sm2 = "SM2";
    public String _protocol;
    public String _method;
    public String _pathname;
    public String _host;
    public String _app_id;
    public String _format;
    public String _charset;
    public String _sign_type;
    public String _timestamp;
    public String _version;
    public String _notify_url;
    public String _mchPrivateKey;
    public String _hyPublicKey;
    public Client(Config config) throws Exception {
        this._protocol = config.protocol;
        this._method = config.method;
        this._pathname = config.pathname;
        this._host = config.host;
        this._app_id = config.app_id;
        this._format = config.format;
        this._charset = config.charset;
        this._sign_type = config.sign_type;
        this._timestamp = config.timestamp;
        this._version = config.version;
        this._notify_url = config.notify_url;
        this._mchPrivateKey = config.mchPrivateKey;
        this._hyPublicKey = config.hyPublicKey;
    }

    //请求接口（除文件上传）

    public ApiResponse callApi(String method, Object bizRequest) throws Exception {
        java.util.Map<String, Object> runtime_ = TeaConverter.buildMap(
                new TeaPair("timeout", 10000),
                new TeaPair("readTimeout", 15000),
                new TeaPair("retry", TeaConverter.buildMap(
                        new TeaPair("maxAttempts", 0)
                ))
        );

        TeaRequest _lastRequest = null;
        Exception _lastException = null;
        long _now = System.currentTimeMillis();
        int _retryTimes = 0;
        while (Tea.allowRetry((java.util.Map<String, Object>) runtime_.get("retry"), _retryTimes, _now)) {
            if (_retryTimes > 0) {
                int backoffTime = Tea.getBackoffTime(runtime_.get("backoff"), _retryTimes);
                if (backoffTime > 0) {
                    Tea.sleep(backoffTime);
                }
            }
            _retryTimes = _retryTimes + 1;
            try {
                TeaRequest request_ = new TeaRequest();
                request_.protocol = _protocol;
                request_.method = _method;
                request_.pathname = _pathname;
                request_.headers = TeaConverter.buildMap(
                        new TeaPair("host", _host),
                        new TeaPair("accept", "application/json"),
                        new TeaPair("content-type", "application/json; charset=utf-8")
                );
                java.util.Map<String, Object> requestParam = TeaConverter.buildMap(
                        new TeaPair("method", method),
                        new TeaPair("app_id", _app_id),
                        new TeaPair("format", _format),
                        new TeaPair("charset", _charset),
                        new TeaPair("sign_type", _sign_type),
                        new TeaPair("timestamp", _timestamp),
                        new TeaPair("version", _version),
                        new TeaPair("notify_url", _notify_url),
                        new TeaPair("biz_content", bizRequest)
                );
                //签名
                String sign = com.hynet.customer.client.common.HynetUtil.sign(requestParam, _mchPrivateKey,_sign_type);
                requestParam.put("sign", sign);
                request_.body = Tea.toReadable(com.aliyun.teautil.Common.toJSONString(requestParam));
                _lastRequest = request_;

                System.out.println("RequestParam -------->>>>>> " + JSON.toJSONString(requestParam, true));

                TeaResponse response_ = Tea.doAction(request_, runtime_);

                java.util.Map<String, Object> result = com.aliyun.teautil.Common.assertAsMap(com.aliyun.teautil.Common.readAsJSON(response_.body));


/*                result.forEach((s, o) -> {
                    System.out.println(s + "-------->>>>>> " + o);
                });*/


                if (!com.aliyun.teautil.Common.equalNumber(response_.statusCode, 200)) {
                    throw new TeaException(TeaConverter.buildMap(
                            new TeaPair("message", "sub_code:" + result.get("sub_code") + " sub_msg:" + result.get("sub_msg") + ""),
                            new TeaPair("code", "" + result.get("code") + "")
                    ));
                }

                java.util.Map<String, String> retMap = com.aliyun.teautil.Common.stringifyMapValue(result);

/*                retMap.forEach((s, o) -> {
                    System.out.println(s + "------M-->>>>>> " + o);
                });*/




                if (!com.aliyun.teautil.Common.equalString(retMap.get("code"), "10000")) {
                    throw new TeaException(TeaConverter.buildMap(
                            new TeaPair("message", "sub_code:" + result.get("sub_code") + " sub_msg:" + result.get("sub_msg") + ""),
                            new TeaPair("code", "" + result.get("code") + "")
                    ));
                }

                Boolean flag =null;


                System.out.println("同步验签结果 -------->>>>>>"+ com.hynet.customer.client.common.HynetUtil.verify(result, _hyPublicKey, retMap.get("sign"),_sign_type));


                if (flag) {
                    java.util.Map<String, Object> bizMap = com.aliyun.teautil.Common.assertAsMap(com.aliyun.teautil.Common.parseJSON(com.aliyun.teautil.Common.toJSONString(result.get("biz_content"))));
                    result.put("biz_content", bizMap);
                    return TeaModel.toModel(result, new ApiResponse());
                }
            } catch (Exception e) {
                if (Tea.isRetryable(e)) {
                    _lastException = e;
                    continue;
                }
                throw e;
            }
        }

        throw new TeaUnretryableException(_lastRequest, _lastException);
    }







    public ApiResponse uploadApi(String method, String credentialType, String filePath) throws Exception {
        java.util.Map<String, Object> runtime_ = TeaConverter.buildMap(
                new TeaPair("timeout", 10000),
                new TeaPair("readTimeout", 15000),
                new TeaPair("retry", TeaConverter.buildMap(
                        new TeaPair("maxAttempts", 0)
                ))
        );

        TeaRequest _lastRequest = null;
        Exception _lastException = null;
        long _now = System.currentTimeMillis();
        int _retryTimes = 0;
        while (Tea.allowRetry((java.util.Map<String, Object>) runtime_.get("retry"), _retryTimes, _now)) {
            if (_retryTimes > 0) {
                int backoffTime = Tea.getBackoffTime(runtime_.get("backoff"), _retryTimes);
                if (backoffTime > 0) {
                    Tea.sleep(backoffTime);
                }
            }
            _retryTimes = _retryTimes + 1;
            try {
                TeaRequest request_ = new TeaRequest();
                String boundary = com.hynet.customer.client.common.HynetUtil.GetRandomBoundary();
                String contentType = "multipart/form-data;";
                request_.protocol = _protocol;
                request_.method = _method;
                request_.pathname = _pathname;
                request_.headers = TeaConverter.buildMap(
                        new TeaPair("host", _host),
                        new TeaPair("content-type", "" + contentType+"boundary="+boundary)
                );
                java.util.Map<String, Object> requestParam = TeaConverter.buildMap(
                        new TeaPair("method", method),
                        new TeaPair("app_id", _app_id),
                        new TeaPair("format", _format),
                        new TeaPair("charset", _charset),
                        new TeaPair("sign_type", _sign_type),
                        new TeaPair("timestamp", _timestamp),
                        new TeaPair("version", _version)
                );
                //获取文件MD5摘要
                String fileMD5 = com.hynet.customer.client.common.HynetUtil.getFileMD5(filePath);
                requestParam.put("file_sign", fileMD5);
                requestParam.put("credential_type", credentialType);
                //签名
                String sign = com.hynet.customer.client.common.HynetUtil.sign(requestParam, _mchPrivateKey,_sign_type);
                requestParam.put("sign", sign);
                request_.body = com.hynet.customer.client.common.HynetUtil.toMultipartRequestBody(requestParam, filePath, boundary);
                _lastRequest = request_;

                System.out.println("RequestParam -------->>>>>> " + JSON.toJSONString(requestParam, true));

                //输出请求参数



                TeaResponse response_ = Tea.doAction(request_, runtime_);

                java.util.Map<String, Object> result = com.aliyun.teautil.Common.assertAsMap(com.aliyun.teautil.Common.readAsJSON(response_.body));
                if (!com.aliyun.teautil.Common.equalNumber(response_.statusCode, 200)) {
                    throw new TeaException(TeaConverter.buildMap(
                            new TeaPair("message", "sub_code:" + result.get("sub_code") + " sub_msg:" + result.get("sub_msg") + ""),
                            new TeaPair("code", "" + result.get("code") + "")
                    ));
                }

                java.util.Map<String, String> retMap = com.aliyun.teautil.Common.stringifyMapValue(result);
                if (!com.aliyun.teautil.Common.equalString(retMap.get("code"), "10000")) {
                    throw new TeaException(TeaConverter.buildMap(
                            new TeaPair("message", "sub_code:" + result.get("sub_code") + " sub_msg:" + result.get("sub_msg") + ""),
                            new TeaPair("code", "" + result.get("code") + "")
                    ));
                }

                Boolean flag =null;

                System.out.println("同步验签结果 -------->>>>>>"+ com.hynet.customer.client.common.HynetUtil.verify(result, _hyPublicKey, retMap.get("sign"),_sign_type));

                if (flag) {
                    java.util.Map<String, Object> bizMap = com.aliyun.teautil.Common.assertAsMap(com.aliyun.teautil.Common.parseJSON(com.aliyun.teautil.Common.toJSONString(result.get("biz_content"))));
                    result.put("biz_content", bizMap);
                    return TeaModel.toModel(result, new ApiResponse());
                }
            } catch (Exception e) {
                if (Tea.isRetryable(e)) {
                    _lastException = e;
                    continue;
                }
                throw e;
            }
        }

        throw new TeaUnretryableException(_lastRequest, _lastException);
    }

}
